package cn.ratel.db;

import cn.ratel.component.Constants;
import cn.ratel.kit.StrKit;
import cn.ratel.tool.ClassSearcher;

import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

class TableBuilder {
	private static Map<String, Table> tableMap = new HashMap<>();

	static void addTable(Table table) {
		tableMap.put(table.name, table);
	}

	static Table getTable(Class<?> modelClazz) {
		String simpleName = modelClazz.getSimpleName();
		if (simpleName.contains("$$EnhancerByCGLIB$$")) {
			simpleName = modelClazz.getSuperclass().getSimpleName();
		}
		return tableMap.get(StrKit.firstCharToLowerCase(simpleName));
	}

	static Map<String, Table> getTableMap() {
		return tableMap;
	}

	static Table addColumn(Table table, ResultSet rs) throws SQLException {
		String columnName = rs.getString("COLUMN_NAME");
		String typeName = rs.getString("TYPE_NAME");
		int dataType = rs.getInt("DATA_TYPE");
		int columnSize = rs.getInt("COLUMN_SIZE");
		boolean isNullable = rs.getBoolean("IS_NULLABLE");
		table.addColumn(new Column(columnName, typeName, dataType, columnSize, isNullable));
		return table;
	}

	static Set<String> getTableNames(DatabaseMetaData metaData) throws SQLException {
		Set<String> tableSet = new HashSet<>();
		ResultSet tablesRs = metaData.getTables(null, null, null, new String[]{"TABLE"});
		while (tablesRs.next()) {
			String tableName = tablesRs.getString("TABLE_NAME");
			tableSet.add(tableName);
		}
		return tableSet;
	}

	static Set<Class<?>> getModels() {
		return ClassSearcher.scan(Constants.me().getScanPackage(), e -> e.getAnnotation(cn.ratel.ioc.annotation.Model.class) != null);
	}
}
